#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <unistd.h>
#include "common.h"

#define MAX_COMMAND_LENGTH 1024
#define MAX_TOKEN_COUNT 128
#define ERROR_IN_FORK "Error in fork\n"
#define CANNOT_EXECUTE "Could not execute command '%s'\n"

//executes the command in current process
void do_execute_command(char * command) 
{
  // args is allocated, but there will be no free(args)
  // it won't make memory leak, beacuse 
  // this process will exec or exit 
  char * * args = my_malloc(MAX_TOKEN_COUNT * sizeof(char));
  split(command, " ", args);
  if (execvp(args[0], args) < 0) {
    printf(CANNOT_EXECUTE, command);
    exit(1);
  } 
}

//executes command in new process
void execute_command(char * command) 
{
    int result = fork();
    if (result < 0) {
	printf(ERROR_IN_FORK);
    }
    else if (result == 0) {
	do_execute_command(command);
    }
    else {
	wait(0);
    }
}

int main() 
{
    char command[MAX_COMMAND_LENGTH];
    int stop = 0;
    while (!stop)
    {
	printf("] ");
	get_command(command);
	if (strcmp(command, "exit") == 0)
            stop = 1;
	else
	    execute_command(command);
    }
    return 0;
}
